<script>
export default {
  name: 'goods component',
  inject: [ 'goods' ],
  methods: {
    add(id) {
        // 找到当前用户的购物车
        // 尝试从 sessionStorage 中获取购物车
        let cart = sessionStorage.getItem( 'shoppingCart' );
        cart = cart ? JSON.parse(cart) : [];
        // 找到指定的商品
        let g = this.goods.find( e => e.id == id );
        if( g.stock > 0 ) {
            console.log( cart );
            // 将商品添加到购物车
            let item = cart.find( e => e.id == id );
            console.log( item );
            if( item ) {
                item.amount++;
            } else {
                cart.push({
                    id: g.id,
                    name: g.name,
                    price: g.price,
                    amount: 1
                });
            }
            // 商品库存数量减少
            g.stock--;
            // 在 sessionStorage 中添加 购物车
            sessionStorage.setItem( 'shoppingCart', JSON.stringify(cart) );
        }
    }
  }
}
</script>

<template>
  <div class="goods-list">
    <el-row v-for="(g,index) in goods" :key="g.id" class="goods" align="middle">
        <el-col :span="4">{{index+1}}</el-col>
        <el-col :span="10">{{g.name}}</el-col>
        <el-col :span="4">{{g.price}}</el-col>
        <el-col :span="3">{{g.stock}}</el-col>
        <el-col :span="3">
            <el-button type="primary" size="small" @click="add(g.id)">添加</el-button>
        </el-col>
    </el-row>
  </div>
</template>

<style>
.goods-list {
    margin: 10px;
}
.goods {
    height: 50px;
    border: 1px solid gray;
    margin: 10px;
}
</style>